package com.mano.mall.service.member.impl;

import com.alibaba.fastjson.JSONObject;
import com.mano.mall.api.dto.member.input.UserInputDTO;
import com.mano.mall.api.member.MemberRegisterService;
import com.mano.mall.common.base.BaseApiService;
import com.mano.mall.common.base.BaseResponse;
import com.mano.mall.common.constants.Constants;
import com.mano.mall.common.utils.MD5Util;
import com.mano.mall.common.utils.MyBeanUtils;
import com.mano.mall.service.feign.VerificaCodeServiceFeign;
import com.mano.mall.service.mapper.UserMapper;
import com.mano.mall.service.mapper.entity.UserDO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
public class MemberRegisterServiceImpl extends BaseApiService<JSONObject> implements MemberRegisterService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private VerificaCodeServiceFeign verificaCodeServiceFeign;

	@Override
	public BaseResponse<JSONObject> register(@RequestBody @Valid UserInputDTO userInputDTO, String registCode) {

		// 1.验证参数
//		String userName = userInputDTO.getUserName();
//		if (StringUtils.isEmpty(userName)) {
//			return setResultError("用户名称不能为空!");
//		}
		String mobile = userInputDTO.getMobile();
		if (StringUtils.isEmpty(mobile)) {
			return setResultError("手机号码不能为空!");
		}
		String password = userInputDTO.getPassword();
		if (StringUtils.isEmpty(password)) {
			return setResultError("密码不能为空!");
		}
		String newPassWord = MD5Util.MD5(password);
		// 将密码采用MD5加密
		userInputDTO.setPassword(newPassWord);
		// 调用微信接口,验证注册码是否正确
		BaseResponse<JSONObject> resultVerificaWeixinCode = verificaCodeServiceFeign.verificaWeixinCode(mobile,
				registCode);
		if (!resultVerificaWeixinCode.getCode().equals(Constants.HTTP_RES_CODE_200)) {
			return setResultError(resultVerificaWeixinCode.getMsg());
		}

		// 判断是否注册过
		UserDO old = userMapper.existMobile(mobile);
		if(null!=old){
			return setResultError("该号码："+mobile+"已经注册会员，请直接登录");
		}

		UserDO userDO = MyBeanUtils.dtoToDo(userInputDTO, UserDO.class);

		int registerResult = userMapper.register(userDO);
		return registerResult > 0 ? setResultSuccess("注册成功") : setResultSuccess("注册失败");

	}

}
